<?php

namespace Biz\pockets\modelTrait;

trait BizModelAdminUserTrait
{
    use BizModelTrait;

    static array $storageName = [];
    static array $storageId = [];

    public static function searchId($id, $separator = ',')
    {
        $idArr = [];
        if (is_array($id)) {
            $idArr = $id;
        } else {
            if (!empty($id)) {
                $idArr = explode($separator, $id);
            }
        }
        foreach ($idArr as $item) {
            if (is_scalar($item) && strlen($item)) self::$storageId[$item] = $item;
        }
    }

    /**
     * 调用 getRowsMapByUniq 后使用
     * */
    public static function afterGetRowsMap($admIds)
    {
        $ids = is_scalar($admIds) ? [$admIds] : $admIds;
        $name = [];
        if (empty(self::$storageName)) self::getNameByUsername(array_values(self::$storageId));
        if ($ids) {
            foreach ($ids as $id) {
                $name[] = self::$storageName[$id] ?? $id;
            }
        }
        return is_scalar($admIds) ? current($name) : $name;
    }

    /**
     * 通过 $index_key 可以得到 id 的名字映射
     * */
    public static function getNameByUsername($ids = [], $condition = []): array
    {
        return self::getRowsMapByUniq($ids, $condition, 'username', 'name');
    }

    public static function getActiveNameByIds($ids = []): array
    {
        return self::getNameByUsername($ids, ['deleted_at' => null]);
    }

    private static function getRowsMapByUniq($ids = [], $condition = [], $index_key = '', $column_key = ''): array
    {
        $users = self::dataSelect($condition + ($ids ? [$index_key => $ids] : []));
        return self::$storageName = $users ? array_column($users, $column_key, $index_key) : [];
    }

}